package com.ems.scheduled;

import com.ems.service.IBatteryBoxService;
import com.ems.service.IBatteryStatisticsDayService;
import com.ems.service.IDeviceService;
import com.ems.vo.BatteryBoxVo;
import com.ems.vo.BatteryStatisticsDayVo;
import com.ems.vo.DeviceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@EnableScheduling
public class BatteryStatisticsScheduled {

    @Resource
    private IBatteryBoxService iBatteryBoxService;
    @Resource
    private IBatteryStatisticsDayService iBatteryStatisticsDayService;
    @Resource
    private IDeviceService iDeviceService;

    //每日凌晨备份前一天所有BMS数据
    @Scheduled ( cron = "0 10 0 * * ?" )
    public void start () {
        LocalDateTime now = LocalDateTime.now ();
        log.info ( "{}-{}-{} {}:{}:{} 备份", now.getYear (), now.getMonth (), now.getDayOfMonth (), now.getHour (), now.getMinute (), now.getSecond () );
        //查询所有BMS
        BatteryBoxVo batteryBoxVo = new BatteryBoxVo ();
        LocalDate localDate = LocalDate.now ().minusDays ( 1 );//1代表提前一天
        batteryBoxVo.setCreateTime ( Date.from ( localDate.atStartOfDay ( ZoneId.systemDefault () ).toInstant () ) );
        List<BatteryBoxVo> batteryBoxVos = iBatteryBoxService.queryMaxDataForDay ( batteryBoxVo );
        for ( BatteryBoxVo boxVo : batteryBoxVos ) {
            BatteryStatisticsDayVo batteryStatisticsDayVo = new BatteryStatisticsDayVo ();
            batteryStatisticsDayVo.setDayChargeCapacity ( boxVo.getDayChargeAmount () );
            batteryStatisticsDayVo.setDayDisChargeCapacity ( boxVo.getDayDischargeAmount () );
            batteryStatisticsDayVo.setTotalChargeCapacity ( boxVo.getTotalChargeAmount () );
            batteryStatisticsDayVo.setTotalDisChargeCapacity ( boxVo.getTotalDischargeAmount () );
            batteryStatisticsDayVo.setDataTime ( boxVo.getCreateTime () );
            batteryStatisticsDayVo.setDeviceAddress ( boxVo.getDeviceAddress () );
            //获取设备所属电站
            DeviceVo deviceVo = new DeviceVo ();
            deviceVo.setDeviceAddress ( boxVo.getDeviceAddress () );
            deviceVo = iDeviceService.querySingle ( deviceVo );
            batteryStatisticsDayVo.setStationId ( deviceVo.getStationId () );
            iBatteryStatisticsDayService.saveSingle ( batteryStatisticsDayVo );
        }
    }
}
